package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.datasource.entities.Depot;
import com.jsh.erp.datasource.entities.DepotEx;
import com.jsh.erp.datasource.entities.MaterialInitialStock;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;


@RestController
@RequestMapping(value = "/depot")
@Api(tags = {"仓库管理"})
public class DepotController {
    private Logger logger = LoggerFactory.getLogger(DepotController.class);

    @Resource
    private DepotService depotService;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private MaterialService materialService;


    /**
     * 系统管理——用户管理——分配仓库
     */
    @GetMapping(value = "/findUserDepot")
    @ApiOperation(value = "分配仓库时查询仓库列表")
    public JSONArray findUserDepot(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId,
                                 HttpServletRequest request) throws Exception{
        JSONArray arr = new JSONArray();
        try {
            //获取权限信息
            String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
            List<Depot> dataList = depotService.findUserDepot();
            //开始拼接json数据
            JSONObject outer = new JSONObject();
            outer.put("id", 0);
            outer.put("key", 0);
            outer.put("value", 0);
            outer.put("title", "仓库列表");
            outer.put("attributes", "仓库列表");
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (Depot depot : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", depot.getId());
                    item.put("key", depot.getId());
                    item.put("value", depot.getId());
                    item.put("title", depot.getName());
                    item.put("attributes", depot.getName());
                    Boolean flag = ubValue.contains("[" + depot.getId().toString() + "]");
                    if (flag) {
                        item.put("checked", true);
                    }
                    dataArray.add(item);
                }
            }
            outer.put("children", dataArray);
            arr.add(outer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return arr;
    }

    /**
     * 零售管理——零售出库——查询列表，新增，编辑
     *          零售退货——查询列表，新增，编辑
     * 采购管理——请购单——新增
     *         采购订单——新增，复制，编辑
     *         采购入库——查询列表，新增，编辑，复制
     *         采购退货——查询列表，新增，编辑，编辑
     * 销售管理——销售订单——新增
     *          销售出库——查询列表，新增，编辑，复制
     *          销售退货——查询列表，新增，编辑，复制
     * 报表查询——商品库存——查询列表
     *          采购统计——查询列表
     *          销售统计——查询列表
     *          零售统计——查询列表
     *          入库明细——查询列表
     *          出库明细——查询列表
     *          进销存统计——查询列表
     *          库存预警——查询列表
     */
    @GetMapping(value = "/findDepotByCurrentUser")
    @ApiOperation(value = "获取当前用户拥有权限的仓库列表")
    public BaseResponseInfo findDepotByCurrentUser(HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            JSONArray arr = depotService.findDepotByCurrentUser();
            res.code = ErpInfo.OK.code;
            res.data = arr;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            res.code = ErpInfo.ERROR.code;
            res.data = ErpInfo.ERROR.name;
        }
        return res;
    }

    /**
     * 商品管理——商品信息——新增时mid为0，编辑
     */
    @GetMapping(value = "/getAllListWithStock")
    @ApiOperation(value = "获取该商品各个仓库的库存")
    public BaseResponseInfo getAllList(@RequestParam("mId") Long mId,
                                       HttpServletRequest request) {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            List<Depot> list = depotService.getAllList();
            List<DepotEx> depotList = new ArrayList<DepotEx>();
            for(Depot depot: list) {
                DepotEx de = new DepotEx();
                if(mId!=0) {
                    //获取商品在某仓库的初始库存
                    BigDecimal initStock = materialService.getInitStock(mId, depot.getId());
                    de.setInitStock(initStock);
                    //获取商品在某仓库的现有库存
                    BigDecimal currentStock = materialService.getCurrentStockByMaterialIdAndDepotId(mId, depot.getId());
                    de.setCurrentStock(currentStock);
                    //获取商品在某仓库的安全库存
                    MaterialInitialStock materialInitialStock = materialService.getSafeStock(mId, depot.getId());
                    de.setLowSafeStock(materialInitialStock.getLowSafeStock());
                    de.setHighSafeStock(materialInitialStock.getHighSafeStock());
                } else {
                    de.setInitStock(BigDecimal.ZERO);    //新增时设置初始库存为0
                    de.setCurrentStock(BigDecimal.ZERO); //新增时设置现有库存为0
                }
                de.setId(depot.getId());
                de.setName(depot.getName());
                depotList.add(de);
            }
            res.code = ErpInfo.OK.code;
            res.data = depotList;
        } catch(Exception e){
            logger.error(e.getMessage(), e);
            res.code = ErpInfo.ERROR.code;
            res.data = ErpInfo.ERROR.name;
        }
        return res;
    }

    /**
     * 基本资料——仓库信息——设为默认仓库
     */
    @PostMapping(value = "/updateIsDefault")
    @ApiOperation(value = "设为默认仓库")
    public String updateIsDefault(@RequestBody JSONObject object,
                                       HttpServletRequest request) throws Exception{
        Long depotId = object.getLong("id");
        Map<String, Object> objectMap = new HashMap<>();
        int res = depotService.updateIsDefault(depotId);
        if(res > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

    /**
     * 基本资料——仓库信息——批量设置状态-启用或者禁用
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request)throws Exception {
        Boolean status = jsonObject.getBoolean("status");
        String ids = jsonObject.getString("ids");
        Map<String, Object> objectMap = new HashMap<>();
        int res = depotService.batchSetStatus(status, ids);
        if(res > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }
}
